"""
门户网站 - 新闻接口
"""
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func

from app.dependencies import get_db
from app.schemas.common import ResponseModel, PaginatedResponse
from app.models.content import News
from app.schemas.content import NewsResponse


router = APIRouter()


@router.get("", response_model=ResponseModel)
async def get_news_list(
    page: int = Query(1, ge=1),
    page_size: int = Query(10, ge=1, le=100),
    category_id: Optional[int] = Query(None),
    keyword: Optional[str] = Query(None),
    db: AsyncSession = Depends(get_db)
):
    """
    获取新闻列表
    """
    query = select(News).where(News.status == 1)
    count_query = select(func.count(News.id)).where(News.status == 1)
    
    # 分类筛选
    if category_id:
        query = query.where(News.category_id == category_id)
        count_query = count_query.where(News.category_id == category_id)
    
    # 关键词搜索
    if keyword:
        query = query.where(News.title.like(f"%{keyword}%"))
        count_query = count_query.where(News.title.like(f"%{keyword}%"))
    
    # 排序和分页（置顶优先）
    query = query.order_by(News.is_top.desc(), News.publish_time.desc())
    skip = (page - 1) * page_size
    query = query.offset(skip).limit(page_size)
    
    # 执行查询
    result = await db.execute(query)
    news_list = result.scalars().all()
    
    count_result = await db.execute(count_query)
    total = count_result.scalar_one()
    
    return ResponseModel(
        data=PaginatedResponse(
            total=total,
            page=page,
            page_size=page_size,
            items=[NewsResponse.model_validate(n) for n in news_list]
        )
    )


@router.get("/{news_id}", response_model=ResponseModel)
async def get_news(
    news_id: int,
    db: AsyncSession = Depends(get_db)
):
    """
    获取新闻详情
    """
    result = await db.execute(
        select(News).where(News.id == news_id, News.status == 1)
    )
    news = result.scalar_one_or_none()
    
    if not news:
        raise HTTPException(status_code=404, detail="新闻不存在")
    
    # 更新浏览量
    news.view_count += 1
    await db.commit()
    await db.refresh(news)
    
    return ResponseModel(data=NewsResponse.model_validate(news))

